var WxParse = require('../../wxParse/wxParse.js');

let app = getApp()

Page({
  onShareAppMessage: function (res) {
    var goods_name = this.data.goods_name
    var u = wx.getStorageSync('u');
    var rec = 'u' + u + 's' + this.data.goods_info.shop_id + 'c' + this.data.goods_info.common_id
    return {
      title: goods_name,
      path: '/pages/product_detail/product_detail?goods_id=' + this.data.goods_id + 'rec=' + rec,
    }
  },
  /**
   * 页面的初始数据
   */

  data: {
    showView: false,
    swiper_img: [],
    swiper_height: "0",
    goods_info: [],
    spec: '',
    store_info: [],
    goods_hair_info: '',
    favorites: "", //判断商品是否收藏改变文字  已收藏 收藏改为 已收藏  未收藏 ""
    active: "",   //判断商品是否收藏改变样式  已收藏-active  未收藏 ""
    is_favorites: 1, //判断商品是否收藏  1 否  2 是
    common_body: '',
    goods: {},
    goods_stock: '',//不同规格库存
    goods_price: '',//不同规格加个
    num: 1,//数量
    goods_id: '',//商品id
    is_lunbo: 0,
    goods_spec: [],
    spec_list_info: [],
    is_show_time: 1,
    stock_list: [],//根据规格选库存
    goods_name: '',
    info: '',
    up_sale: false,
    up_voucher: false,

    windowHeight: 654,
    maxtime: "",
    isHiddenLoading: true,
    isHiddenToast: true,
    dataList: {},
    countDownDay: 0,
    countDownHour: 0,
    countDownMinute: 0,
    countDownSecond: 0,

    data_min: '',
    data_max: '',
    data_min: 1,
    promotion: '',
	showadd: false,
	shop_id: '',
	statusBarHeight: app.globalData.statusBarHeight,

  },
  // 自定义事件 用来接收子组件传递的数据的
   handleItemChange(e){
		// 接收传递过来的参数
		const {index,shop_id}=e.detail;
  		if(index) {
			if(shop_id) {
				wx.navigateTo({
				  url: "../store/store?shop_id=" + shop_id
				})
			} else {
				wx.switchTab({
					url: '../web_view/web_view'
				})
			}
		} else {
			wx.navigateBack(-1)
		}
   },

  /**
   * 生命周期函数--监听页面加载
   */

onLoad: function (options) {
  var showadd = options.showadd || false
  var shop_id = options.shop_id || ''
  
  // 获取系统信息
  const systemInfo = wx.getSystemInfoSync()
  const windowHeight = systemInfo.windowHeight
  const windowWidth = systemInfo.windowWidth
  
  this.setData({
    windowHeight: windowHeight,
    swiper_height: windowWidth, // 轮播图高度等于屏幕宽度
    showadd: showadd,
    shop_id: shop_id,
    statusBarHeight: app.globalData.statusBarHeight
  });
  
  var that = this;
  new app.ToastPannel();
  var goods_id = options.goods_id
  var rec = options.rec
  if (rec) {
    wx.setStorage({
      key: 'rec',
      data: rec,
    })
  }
  that.requests(goods_id, 1)
  that.cart_num()
  
  wx.request({
    url: app.configData.shop.api_url + '/index.php?ctl=Goods_Goods&met=getCommonDetail&typ=json',
    method: 'GET',
    data: { goods_id: goods_id },
    header: {
      'content-type': 'application/json'
    },
    success: function (res) {
      if (res.data.status == 200) {
        var common_body = res.data.data.common_body
        WxParse.wxParse('common_body', 'html', common_body, that, 5);
      }
    }
  })
},

    // 在cart_num方法之前添加客服相关方法
  /**
   * 客服会话成功回调
   */
  handleContactSuccess: function(e) {
    console.log('客服会话建立成功', e.detail);
    
    // 记录用户咨询行为（可选）
    this.recordConsultBehavior();
  },

  /**
   * 记录用户咨询行为（用于数据分析）
   */
  recordConsultBehavior: function() {
    const that = this;
    const key = wx.getStorageSync('key');
    const uid = wx.getStorageSync('u');
    
    if (key && uid && that.data.goods_id) {
      // 这里可以调用你的统计接口
      console.log('用户咨询商品:', {
        goods_id: that.data.goods_id,
        goods_name: that.data.goods_info.goods_name,
        user_id: uid
      });
      
      // 如果需要发送到服务器，取消注释下面的代码
      /*
      wx.request({
        url: app.configData.shop.api_url + '/index.php?ctl=Buyer_Behavior&met=recordConsult&typ=json',
        method: 'POST',
        data: { 
          k: key, 
          u: uid, 
          goods_id: that.data.goods_id,
          goods_name: that.data.goods_info.goods_name,
          timestamp: new Date().getTime()
        },
        header: {
          'content-type': 'application/json'
        },
        success: function (res) {
          console.log('咨询行为记录成功', res);
        }
      });
      */
    }
  },
  
  cart_num: function () {
    var that = this
    var k = wx.getStorageSync('key');
    var u = wx.getStorageSync('u');
    wx.request({
      url: app.configData.shop.api_url + '/index.php?ctl=Buyer_Cart&met=cart&typ=json',
      method: 'GET',
      data: { k: k, u: u },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {

        that.setData({
          cart_num: res.data.data.number
        })
      }
    })
  },
  //购买数量添加
  add: function (e) {

    var that = this
    var num = that.data.num
    var data_max = that.data.data_max
    var goods_stock = e.currentTarget.dataset.count
    if (Number(num) >= Number(goods_stock)) {
      that.show('已超出商品库存')
      return
    }
    if (Number(num) + 1 >= data_max && data_max > 0) {
      if (Number(num) == data_max && Number(num) > 0) {
        that.show('每个用户最多只能购买' + data_max + '件')
      }
      that.setData({
        num: data_max
      })
    } else {
      num++
      that.setData({
        num: num
      })
    }


  },
  toStore: function (e) {
    var store_id = e.currentTarget.dataset.shop_id
    wx.navigateTo({
      url: "../store/store?shop_id=" + store_id
    })
  },
  //购买数量减少
  reduce: function (e) {
    var that = this
    var num = that.data.num
    if (Number(num) > that.data.data_min) {
      that.setData({
        num: Number(num) - 1
      })
    } else {
      if (that.data.promotion == 1) {
        that.show('该限时折扣商品最少需购买' + that.data.data_min + '件')
      } else {
        that.show('该商品最少需购买' + that.data.data_min + '件')
      }
    }

  },
  //切换规格
  spec_change: function (e) {

    var that = this
    var specs_value_id = e.currentTarget.dataset.id//规格id
    var pid = e.currentTarget.dataset.pid//规格父级
    var list = that.data.goods_spec

    var goods = that.data.goods//规格属性大项
    var i = 0
    var newlist = {}
    var arr = []
    var spec_list_info = that.data.spec_list_info
    var stock_list = that.data.stock_list
    var goods_id = ''
    var goods_stock = ''
    arr.push(Number(specs_value_id))
    for (var x in list) {
      if (specs_value_id == x) {
        return false;
      } else {
        for (var j in goods) {
          if (j == pid) {

            continue;
          } else {
            for (var z in goods[j]) {
              if (z == x) {
                arr.push(Number(z))
              }
            }
          }
        }
      }
    }

    var zz = arr.sort(that.sortNumber).join('|')
    for (var ii in spec_list_info) {
      if (ii == zz) {
        goods_id = spec_list_info[ii]
      }
    }

    for (var ii in stock_list) {
      if (ii == zz) {
        goods_stock = stock_list[ii]
      }
    }

    zz = zz.split("|")
    var w = []
    for (var i = 0; i < zz.length; i++) {
      w[zz[i]] = zz[i]
    }
    that.setData({
      goods_spec: w,
      goods_id: goods_id,
      goods_stock: goods_stock
    })
    that.requests(goods_id, 2)

  },
  sortNumber: function (a, b) {
    return a - b
  },
  //  收藏商品 
  bingfavorites: function (e) {
    var that = this
    var key = wx.getStorageSync('key')
    if (!key) {
      wx.showModal({
      	title: '登录提示',
      	content: '此功能需要登录后才能使用',
      	confirmText: '去登录',
      	cancelText: '再逛逛',
      	success: (res) => {
      	  if (res.confirm) {
      		wx.navigateTo({
      		  url: `/pages/authorize_login/authorize_login`
      		});
      	  }
      	}
      });

    } else {
		var uid = wx.getStorageSync('u')
		var goods_id = e.currentTarget.dataset.goods_id
		var is_favorites = that.data.is_favorites
		var url = ''
		var data = ''
		if (key) {
		
		  if (is_favorites == 1) {
		    url = app.configData.shop.api_url + '/index.php?ctl=Goods_Goods&met=collectGoods&typ=json'
		    data = { goods_id: goods_id, u: uid, k: key }
		  } else {
		    url = app.configData.shop.api_url + '/index.php?ctl=Buyer_Favorites&met=delFavoritesGoods&typ=json'
		    data = { id: goods_id, u: uid, k: key }
		  }
		  wx.request({
		    url: url,
		    method: 'GET',
		    data: data,
		    header: {
		      'content-type': 'application/json'
		    },
		    success: function (res) {
		
		      if (res.data.status == 200) {
		        if (is_favorites == 1) {
		          that.show(res.data.data.msg)
		          that.setData({
		            active: "-active",
		            favorites: "已",
		            is_favorites: 2
		          })
		        } else {
		          that.show('已取消收藏')
		          that.setData({
		            active: "",
		            favorites: "",
		            is_favorites: 1
		          })
		        }
		
		      }
		    }
		  })
		} else {
		  app.set_request()
		}
	}
    


  },
  //数据请求
  requests: function (goods_id, types) {
    var that = this;
    var key = wx.getStorageSync('key')

    var uid = wx.getStorageSync('u')
    var is_lunbo = that.data.is_lunbo
    wx.request({
      url: app.configData.shop.api_url + '/index.php?ctl=Goods_Goods&met=goods&typ=json',
      method: 'GET',
      data: { k: key, u: uid, goods_id: goods_id, ua: 'wap' },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {

        if (res.data.status == 200) {

          var goods_info = res.data.data.goods_info
          var store_info = res.data.data.store_info
          var goods_id = res.data.data.goods_id
          var swiper_img = goods_info.image_row
          var goods_hair_info = res.data.data.goods_hair_info
          var info = res.data.data
          var j = 0
          for (var i in goods_info.image_row) {
            j++
          }
          if (swiper_img == '') {
            swiper_img[0] = goods_info.goods_image
            is_lunbo = 1
          } else if (j == 1) {
            swiper_img[0] = goods_info.image_row[0].images_image
            is_lunbo = 1
          }

          if (res.data.data.is_favorate == true) {
            that.setData({
              active: "-active",
              favorites: "已",
              is_favorites: 2
            })
          }
          if (types == 1) {
            var goods_spec = []
            for (var i in goods_info.goods_spec) {
              goods_spec[i] = goods_info.goods_spec[i]
            }
          } else {
            var goods_spec = that.data.goods_spec
          }

          if (goods_info.promotion_type == 'xianshi' && goods_info.promotion_is_start == 1) {
            if (goods_info.promotion_is_start == 0) {
              that.timeopen(goods_info.groupbuy_starttimes)
            } else {
              that.timeopen(goods_info.groupbuy_endtimes)
            }
          }
          if (info.buyer_limit != 0) {
            if (info.buyer_limit >= goods_info.goods_stock) {
              var data_max = goods_info.goods_stock;
            } else {
              var data_max = info.buyer_limit;
            }
          } else {
            var data_max = info.goods_info.goods_stock;
          }

          if (goods_info.lower_limit > 1 && goods_info.promotion_is_start == 1) {
            var data_min = goods_info.lower_limit;
            var promotion = 1;
            var goods_price = goods_info.promotion_price
          }
          else {
            var data_min = 1;
            var promotion = 0;
            var goods_price = goods_info.goods_price
          }
          that.setData({
            swiper_img: swiper_img,
            goods_info: goods_info,
            spec: goods_info.show_goods_spec_str,//已选中规格
            store_info: store_info,//店铺信息
            goods_hair_info: goods_hair_info,
            goods_id: goods_id,//商品id
            goods: goods_info.spec_list,
            goods_stock: goods_info.goods_stock,//每种规格库存
            stock_list: res.data.data.stock_list,//不同规格库存列表
            goods_price: goods_price,//每种规格加个
            goods_spec: goods_spec,
            spec_list_info: res.data.data.spec_list,
            is_lunbo: is_lunbo,
            is_show_time: 0,
            goods_name: goods_info.common_name,
            info: info,
            data_max: data_max,
            num: data_min,
            data_min: data_min,
            promotion: promotion
          });

        } else if (res.data.status == 404) {
          that.setData({
            is_show_time: 0,
          });
          that.show(res.data.msg)
          setTimeout(function () {
            wx.navigateBack({
              delta: -1
            })
          }, 2000)

        }
      }
    })
  },
  //选择规格
  changespec: function () {
    var that = this;
    that.setData({
      showView: (!that.data.showView),

    })
  },

  //关闭
  off: function () {
    var that = this;

    that.setData({
      showView: (!that.data.showView),
    })

  },
  sure: function (e) {
    var that = this
    that.setData({
      showView: (!that.data.showView),
    })

  },

  //跳转至购物车页面
  goCart: function () {
    wx.switchTab({
      url: '../cart/cart'
    })
  },
  //加入购物车
	addCart: function (e) {
	  var that = this
	  var types = e.currentTarget.dataset.types
	  var is_huodong = e.currentTarget.dataset.is_huodong
	  var common_is_virtual = e.currentTarget.dataset.common_is_virtual
	  var key = wx.getStorageSync('key')
	  if (!key) {
		wx.showModal({
			title: '登录提示',
			content: '此功能需要登录后才能使用',
			confirmText: '去登录',
			cancelText: '再逛逛',
			success: (res) => {
			  if (res.confirm) {
				wx.navigateTo({
				  url: `/pages/authorize_login/authorize_login`
				});
			  }
			}
		});

	  } else {
		var uid = wx.getStorageSync('u')
		var goods_id = that.data.goods_id
		var goods_num = that.data.num
		var goods_stock = e.currentTarget.dataset.goods_stock
		
		if (is_huodong == 'groupbuy') {
		  that.show('团购活动商品暂不支持在小程序上购买')
		  return false
		}
		// if (common_is_virtual == 1) {
		//   that.show('虚拟产品暂不支持在小程序上购买')
		//   return false
		// }
		if (goods_stock == 0) {
		  that.show('该商品已售空')
		  return false
		}
		wx.request({
		  url: app.configData.shop.api_url + '/index.php?ctl=Buyer_Cart&met=addCart&typ=json',
		  method: 'GET',
		  data: { k: key, u: uid, goods_id: goods_id, goods_num: goods_num },
		  header: {
			'content-type': 'application/json'
		  },
		  success: function (res) {
			if (res.data.status == 200) {
			  that.cart_num()
			  if (types == 'buy') {
				if (common_is_virtual == 1) {
				  // 修改这里：在跳转链接中添加 from=detail 标识
				  wx.redirectTo({
					url: '../vr_buy_step1/vr_buy_step1?product_id=' + res.data.data.cart_id + '&from=detail',
				  })
				} else {
				  // 实物商品也添加同样的标识，保持一致性
				  wx.redirectTo({
					url: '../buy_step1/buy_step1?product_id=' + res.data.data.cart_id + '&from=detail',
				  })
				}
			  } else {
				that.show('加入购物车成功')
			  }
			}
		  }
		})
	  }
	},
  //关闭代金券领取页面
  close_getVoucher: function () {
    this.seTData({
      up_voucher: false
    })
  },
  //调起促销活动页
  for_sale: function () {
    this.setData({
      up_sale: !this.data.up_sale
    })
  },
  //关闭促销活动页
  close_for_sale: function () {
    this.seTData({
      up_sale: false
    })
  },
  //领取代金券
  getVoucher: function (e) {
    this.setData({
      up_voucher: !this.data.up_voucher
    })
  },
  close_mask: function () {
    this.setData({
      up_sale: false,
      up_voucher: false
    })
  },
  // 页面渲染完成后 调用  
  timeopen: function (time) {
    var totalSecond = time - Date.parse(new Date()) / 1000;
    var interval = setInterval(function () {
      // 秒数  
      var second = totalSecond;

      // 天数位  
      var day = Math.floor(second / 3600 / 24);
      var dayStr = day.toString();
      if (dayStr.length == 1) dayStr = '0' + dayStr;

      // 小时位  
      var hr = Math.floor((second - day * 3600 * 24) / 3600);
      var hrStr = hr.toString();
      if (hrStr.length == 1) hrStr = '0' + hrStr;

      // 分钟位  
      var min = Math.floor((second - day * 3600 * 24 - hr * 3600) / 60);
      var minStr = min.toString();
      if (minStr.length == 1) minStr = '0' + minStr;

      // 秒位  
      var sec = second - day * 3600 * 24 - hr * 3600 - min * 60;
      var secStr = sec.toString();
      if (secStr.length == 1) secStr = '0' + secStr;

      this.setData({
        countDownDay: dayStr,
        countDownHour: hrStr,
        countDownMinute: minStr,
        countDownSecond: secStr,
      });
      totalSecond--;
      if (totalSecond < 0) {
        clearInterval(interval);
        wx.showToast({
          title: '活动已结束',
        });
        this.setData({
          countDownDay: '00',
          countDownHour: '00',
          countDownMinute: '00',
          countDownSecond: '00',
        });
      }
    }.bind(this), 1000);
  },
  //立即领取代金券
  receive: function (e) {
    var that = this
    var vid = e.currentTarget.dataset.vid
    var k = wx.getStorageSync('key');
    if (!k) {
      wx.showModal({
      	title: '登录提示',
      	content: '此功能需要登录后才能使用',
      	confirmText: '去登录',
      	cancelText: '再逛逛',
      	success: (res) => {
      	  if (res.confirm) {
      		wx.navigateTo({
      		  url: `/pages/authorize_login/authorize_login`
      		});
      	  }
      	}
      });

    } else {
		var u = wx.getStorageSync('u');
		if (vid) {
		  wx.request({
		    url: app.configData.shop.api_url + '/index.php?ctl=Voucher&met=receiveVoucher&typ=json',
		    method: 'GET',
		    data: { k: k, u: u, vid: vid },
		    header: {
		      'content-type': 'application/json'
		    },
		    success: function (res) {
				console.log(res)
		      that.show(res.data.msg)
		    }
		  })
		}
	}
    
  },
  //门店自提
  ziti: function () {
    var that = this
    var uid = wx.getStorageSync('u')
    var key = wx.getStorageSync('key')
    if (!key) {
      wx.showModal({
      	title: '登录提示',
      	content: '此功能需要登录后才能使用',
      	confirmText: '去登录',
      	cancelText: '再逛逛',
      	success: (res) => {
      	  if (res.confirm) {
      		wx.navigateTo({
      		  url: `/pages/authorize_login/authorize_login`
      		});
      	  }
      	}
      });

    } else {
		var goods_id = that.data.goods_id
		var shop_id = that.data.info.store_info.store_id
		var goods_num = that.data.num
		if (uid == that.data.info.store_info.member_id && uid) {
		  that.show('不能购买自己商店的商品')
		} else {
		  wx.request({
		    url: app.configData.shop.api_url + '/index.php?ctl=Goods_Goods&met=chain&typ=json',
		    method: 'GET',
		    data: { k: key, u: uid, goods_id: goods_id, shop_id: shop_id, goods_num: goods_num },
		    header: {
		      'content-type': 'application/json'
		    },
		    success: function (res) {
		
		      if (res.data.status == 200) {
		        wx.navigateTo({
		          url: '../ziti/ziti?goods_id=' + goods_id + '&shop_id=' + shop_id + '&goods_num=' + goods_num,
		        })
		      } else {
		        that.show(res.data.msg)
		      }
		
		    }
		  })
		
		}
	}
    
  }
})